package controllers

import (
	"mailsrv/models"
	"strings"
)

type MailController struct {
	BaseController
}

/*
应用接入管理
 */
func (this *MailController) MailList(){




	this.setTpl("mail.html")
}

func (this *MailController) MailListApi(){
	page, _ := this.GetInt("page")
	mailReps := models.MailerSrv{}
	datas, total := mailReps.PageList(page)
	this.pageApiJson(datas, total, "", 0)

}


//添加发件箱
func (this *MailController) MailInsert(){



	this.setTpl("mail_insert.html")
}
func (this *MailController) MailEdit(){
	id, _ := this.GetInt("id")
	if id==0{
		this.goError("ID丢失！")
	}
	model := models.MailerSrv{}
	info, _ := model.GetOne(id)

	this.Data["info"] = info
	this.setTpl("mail_edit.html")

}


func (this *MailController) MailEditDo(){
	id, _ := this.GetInt64("id")
	if id==0{
		this.ajaxReturn("", "ID丢失", 400)
	}

	name := strings.TrimSpace(this.GetString("name"))
	mail_host := strings.TrimSpace(this.GetString("mail_host"))
	mail_port,_ := this.GetInt("mail_port")
	mail_secure := strings.TrimSpace(this.GetString("mail_secure"))
	account := strings.TrimSpace(this.GetString("account"))
	password := strings.TrimSpace(this.GetString("password"))
	desc := strings.TrimSpace(this.GetString("desc"))

	params := models.MailerSrv{
		Id:id,
		Name:name,
		Mail_host:mail_host,
		Mail_port:mail_port,
		Mail_secure:mail_secure,
		Account:account,
		Desc:desc,
	}
	if password != ""{
		params.Password = password
	}

	result, _ := params.MailEdit()
	if result <= 0 {
		this.ajaxReturn("", "失败", 400)
	}else{
		this.ajaxReturn(map[string]string{"url":this.URLFor("MailController.MailList")}, "成功", 200)
	}
}


func (this *MailController) MailInsertDo(){
	name := strings.TrimSpace(this.GetString("name"))
	mail_host := strings.TrimSpace(this.GetString("mail_host"))
	mail_port,_ := this.GetInt("mail_port")
	mail_secure := strings.TrimSpace(this.GetString("mail_secure"))
	account := strings.TrimSpace(this.GetString("account"))
	password := strings.TrimSpace(this.GetString("password"))
	desc := strings.TrimSpace(this.GetString("desc"))

	params := models.MailerSrv{
		Name:name,
		Mail_host:mail_host,
		Mail_port:mail_port,
		Mail_secure:mail_secure,
		Account:account,
		Password:password,
		Desc:desc,
	}

	result := params.MailInsert()
	if result != nil {
		error_msg := result.Error()
		this.ajaxReturn("", "添加失败："+error_msg, 400)
	}else{
		this.ajaxReturn(map[string]string{"url":this.URLFor("MailController.MailList")}, "成功", 200)
	}
}


func (this *MailController) MailDelDo(){
	id, _ := this.GetInt64("id")
	if id==0{
		this.goError("ID丢失！")
	}

	apps := models.Apps{}
	exitst,_ := apps.GetOneByMid(id)
	if exitst != nil{
		this.ajaxReturn("", "有业务线正在使用此邮箱，无法删除！", 400)
	}

	mailsrv := models.MailerSrv{}
	_, err := mailsrv.MailSrvDel(id)

	if err != nil {
		this.ajaxReturn("", "删除失败", 400)
	}else{
		this.ajaxReturn("", "成功", 200)
	}
}
